<template>
  <div class="InventoryManage-page-content">
    <div class="InventoryManage-page-form">
      <el-input
        v-model="formData.supplyName"
        style="width: 300px"
        placeholder="供应商名称"
        :suffix-icon="Search"
      />
      <el-button
        type="primary"
        @click="getSupplyListData"
        style="margin-left: 20px"
        >查询</el-button
      >

      <div class="InventoryManage-page-form-right">
        <el-button type="primary" @click="add" v-btnPermission="'btn-supply-add'">新建</el-button>

        <!-- <el-button type="primary" plain>导出</el-button> -->
      </div>
    </div>
    <div class="InventoryManage-page-table">
      <Table
        :columns="tableColumns"
        :loading="loading"
        :data-source="tableData"
      />
    </div>
    <div class="InventoryManage-page-pagination">
      <Pagination
        style="margin-left: auto"
        :key="pageSize + 'Pagination' + currentPage"
        :count="total"
        :page-size="pageSize"
        :pageNo="currentPage"
        @onPagechange="handlePageChange"
        @onSizechange="handleSizeChange"
      />
    </div>
    <updata
      ref="updataRef"
      :data-type="dataType"
      @closeDrawer="getSupplyListData"
    />
    <detailsd
      ref="detailsRef"
    />
  </div>
</template>

<script setup lang="ts">
import { ArrowDown, Search } from '@element-plus/icons-vue';
import type { TableProps, TableColumn } from '@/types/table';
import type { SupplyInfo, SupplyTable, SupplyForm } from '@/types/supply';
import {
  getSupplyList,
  deleteSupply,
  enableSupply,
  disableSupply,
} from '@/api/supply';
import updata from './common/updata.vue';
import detailsd from './common/details.vue';
import type { Action } from 'element-plus';
const updataRef = ref<InstanceType<typeof updata>>();
const detailsRef = ref<InstanceType<typeof detailsd>>();
const dataType = ref<number>(0);
const loading = ref<boolean>(false);
const formData = ref<SupplyForm>({
  supplyName: '',
  pageNo: 1,
  pageSize: 10,
});
import stores from '@/store';

const regions:any = stores.useBaseDataStore().regions;

const add = () => {
  dataType.value = 0;
  updataRef.value?.open();
};

const tableColumns: TableColumn[] = [
    // { prop: 'supplyName', label: '供应商' },
      {
        prop: 'supplyName',
        label: '供应商',
        type: 'text',
        width: 200,
        textColor:'color:#18B3AB',
        componentProps: {
            fixed: 'left',
        },
        buttonGroup: [
            {
                label: 'supplyName', type: 'text', click: (row: any) => {
                    dataType.value = 1
                    detailsRef.value?.open(row);
                }
            },
        ]
    },
    { prop: 'managerName', label: '联系人' },
    { prop: 'managerPhone', label: '联系电话' },
    { prop: 'addressText', label: '联系地址' ,width: 250},
    { prop: 'isEnabled', label: '启用状态' ,type:'tag'},
    { prop: 'createBy', label: '创建人员' },
    { prop: 'createTime', label: '创建时间' },
    { prop: 'updateBy', label: '更新人' },
    { prop: 'updateTime', label: '更新时间' },
    {
        prop: 'action',
        label: '操作',
        type: 'action',
        width: 170,
        componentProps: {
            fixed: 'right',

        },
        buttonGroup: [
            {
                label: '编辑',permissions:'btn-supply-edit', type: 'text', click: (row: SupplyInfo) => {
                    dataType.value = 1
                    updataRef.value?.open1(row)
                }
            },
            {
                label: '启用', statusName: ['isEnabled'],permissions:'btn-supply-enable', status: '停用', type: 'text', click: (row: SupplyInfo) => {
                      enableSupply(row.supplyId ?? 0).then((res) => {
                        if(res.code == '200'){
                             getSupplyListData(); // 刷新列表
                                ElMessage({
                                type: 'success',
                                message: '操作成功',
                                duration: 2000,

                            });
                        }else{
                            //   ElMessage({
                            //     type: 'warning',
                            //     duration: 2000,
                            //     message: res.msg,
                            // });
                        }
                       

                    });
                }
            },
            {
                label: '停用', statusName: ['isEnabled'], permissions:'btn-supply-disable',status: '启用', type: 'text', color: '#D90000', click: (row: SupplyInfo) => {
                    disableSupply(row.supplyId ?? 0).then((res) => {
                       if(res.code == '200'){
                             getSupplyListData(); // 刷新列表
                                ElMessage({
                                type: 'success',
                                message: '操作成功',
                                duration: 2000,

                            });
                        }else{
                            //   ElMessage({
                            //     type: 'warning',
                            //     message: res.msg,
                            //     duration: 2000,

                            // });
                        }

                    });


                }
            },
            {
                label: '删除', type: 'text', color: '#D90000',permissions:'btn-supply-del', click: (row: SupplyInfo) => {
                    //console.log('删除', row)
                    
                    ElMessageBox.alert('确定要删除吗？', '删除供应商', {
                        // if you want to disable its autofocus
                        // autofocus: false,
                        confirmButtonText: '确定',
                        callback: (action: Action) => {
                             if(action == 'cancel'){
                                return;
                            }
                            try {
                                deleteSupply(row.supplyId ?? 0).then((res) => {
                                getSupplyListData(); // 刷新列表
                                ElMessage({
                                    type: 'success',
                                    message: '操作成功',
                                    duration: 2000,

                                });
                                });
                            } catch (error: any) {
                                //console.log(error, '删除失败');

                            }

                        },
                    })
                }
            }
        ]
    }
]
const tableData = ref<SupplyInfo[]>([])
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const getSupplyListData = async()=>{
    loading.value = true
    formData.value.pageNo = currentPage.value;
    formData.value.pageSize = pageSize.value;
   let res = await getSupplyList(formData.value) 
    if(res.code != '200'){
            //ElMessage.error(res.msg);
            return
        }
   res.data.list.forEach((item: any) => {
      item.isEnabled = item.isEnabled === '1' ? '启用' : '停用';
    });
    loading.value = false


   

    for (let index = 0; index < res.data.list.length; index++) {
        let items:any = res.data.list[index];
        let cityList = []
        let countyList = []
        let province = ''
        let city = ''
        let county = ''
        for (let index = 0; index < regions.length; index++) {
          let item = regions[index];
          if(item && items.province){
            if(Number(item.id) == Number(items.province)){
              console.log(item);
              province = item.name
              cityList = item.children
            }
          }
        }
        
        for (let index = 0; index < cityList.length; index++) {
          let item:any = cityList[index];
          if(item && items.city){
            if(Number(item.id) == Number(items.city)){
              city = item.name
              countyList = item.children
            }
          }
        }

        for (let index = 0; index < countyList.length; index++) {
          let item:any = countyList[index];
          if(item && items.county){
            if(Number(item.id) == Number(items.county)){
              county = item.name
            }
          }
        }
        items.addressText = province + city + county + items.address

    }



   tableData.value = res.data.list
   total.value = res.data.totalCount
}
getSupplyListData()




const handlePageChange = (page: number) => {
  //console.log('当前页:', page);
  currentPage.value = page;
  getSupplyListData();
};
const handleSizeChange = (size: number) => {
  //console.log('每页条数:', size);
  currentPage.value = 1;
  pageSize.value = size;
  getSupplyListData();
};
</script>

<style lang="scss">
.InventoryManage {
  padding: 24px;
  height: 100%;
}

.InventoryManage-page {
  background: #fff;
  border-radius: 6px;
  height: 100%;

  .InventoryManage-page-nav {
    display: flex;
    align-items: center;
    justify-content: left;
    border-radius: 4px;
    border-bottom: 1px solid #e7e7e7;

    .el-dropdown-link {
      background: rgba(22, 173, 164, 0.08);
      border-radius: 0px 0px 0px 0px;
      padding: 16px 21px;
      cursor: pointer;
      color: var(--el-color-primary) !important;
      display: flex;
      font-size: 16px;
      align-items: center;
    }
  }

  .InventoryManage-page-content {
    padding: 21px 24px;
    height: calc(100% - 50px);

    .InventoryManage-page-form {
      display: flex;
      align-items: center;

      .InventoryManage-page-form-right {
        margin-left: auto;
      }
    }

    .InventoryManage-page-table {
      margin-top: 22px;
      height: calc(100vh - 300px);
    }

    .InventoryManage-page-pagination {
      margin-top: 24px;
      display: flex;
      align-items: center;

      .InventoryManage-page-pagination-total {
        margin-right: auto;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 400;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.6);
        text-align: left;
        font-style: normal;
        text-transform: none;
      }
    }
  }
}
</style>
